<?php
namespace app\api\service;

use think\Controller;
use think\Db;
use app\api\service\Message;
use app\api\service\Registration;

class Repair extends Controller
{
    static protected $err_code = 0;

    //申请成为维修店接口
    static public function repair_create($param)
    {
        file_put_contents('repair_create_param.txt', '1' . json_encode($param));
        if (!isset($param['member_id']) || !isset($param['repair_name'])
            || !isset($param['province']) || !isset($param['city']) || !isset($param['area']) || !isset($param['street']) || !isset($param['address']) 
            || !isset($param['proposer']) || !isset($param['card_no']) || !isset($param['id_card_in_hand']) || !isset($param['id_card_front']) || !isset($param['id_card_verso'])
            || !isset($param['business_license_name']) || !isset($param['business_license_num']) || !isset($param['business_license'])
            || !isset($param['logo']) || !isset($param['phone'])
            || !isset($param['lat']) || !isset($param['lon'])
        ) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        // 根据地址名称获取地址ID
        $scope = get_scope_id($param['province'], $param['city'], $param['area'], $param['street']);

        $data = [
            'repair_name' => $param['repair_name'],

            'province' => $scope['province'],
            'city' => $scope['city'],
            'area' => $scope['area'],
            'street' => $scope['street'],

            'address' => $param['address'],
            'proposer' => $param['proposer'],
            'card_no' => $param['card_no'],
            'id_card_in_hand' => $param['id_card_in_hand'],
            'id_card_front' => $param['id_card_front'],
            'id_card_verso' => $param['id_card_verso'],
            'business_license_name' => $param['business_license_name'],
            'business_license_num' => $param['business_license_num'],
            'business_license' => $param['business_license'],
//            'open_time' => 0,
//            'close_time' => 0,
            'logo' => $param['logo'],
            'phone' => $param['phone'],
//            'mobile' => '',
//            'ketubbah' => '',
            'apply_time' => time(),
            'audit_status' => 1,
//            'auditor' => '',
//            'audit_time' => '',
//            'msg' => '',
//            'money' => '',
//            'money_frozen' => '',
//            'recommend_order' => '',
//            'role' => '',
            'lat' => $param['lat'],
            'lon' => $param['lon']
        ];
        // 可选参数  有才添加
        if (isset($param['cover']) && $param['cover']) $data['cover'] = $param['cover'];
        if (isset($param['environment_img1']) && $param['environment_img1']) $data['environment_img1'] = $param['environment_img1'];
        if (isset($param['environment_img2']) && $param['environment_img2']) $data['environment_img2'] = $param['environment_img2'];
        if (isset($param['environment_img3']) && $param['environment_img3']) $data['environment_img3'] = $param['environment_img3'];
        if (isset($param['environment_img4']) && $param['environment_img4']) $data['environment_img4'] = $param['environment_img4'];
        if (isset($param['environment_img5']) && $param['environment_img5']) $data['environment_img5'] = $param['environment_img5'];
        if (isset($param['environment_img6']) && $param['environment_img6']) $data['environment_img6'] = $param['environment_img6'];
        if (isset($param['environment_img7']) && $param['environment_img7']) $data['environment_img7'] = $param['environment_img7'];
        if (isset($param['environment_img8']) && $param['environment_img8']) $data['environment_img8'] = $param['environment_img8'];

        // 启动事务
        Db::startTrans();
        try {
            /*调用验证器 验证数据*/
            $validate = validate('Repair');
            //判断是否可以申请
            if (!$validate->check($param)) {
                self::$err_code = $validate->getError();
                throw new \Exception('提交资料不完整，请确认');
            }

            $repair = Db::table('mob_repair')->where('member_id', $param['member_id'])->find();


            if ($repair) {

                Db::table('mob_repair')->where("member_id", $param['member_id'])->update($data);

                Db::table('mob_audit_log')->where('obj_id', $repair["id"])->where('model', 'repair')->delete(); // 重新提交  删除审核记录
                $insert_id = $repair["id"];
            } else {
                // 先检查是否存在信息相同的维修店（店铺名字，身份证，用户）
                $check_repair_name = Db::table('mob_repair')->field('id')->where('repair_name', $param['repair_name'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400050;  //店铺名字重复
                    throw new \Exception('FAULT');
                }
                $check_repair_name = Db::table('mob_repair')->field('id')->where('member_id', $param['member_id'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400052;  //用户已申请维修店
                    throw new \Exception('FAULT');
                }
                $check_repair_name = Db::table('mob_repair')->field('id')->where('card_no', $param['card_no'])->find();
                if ($check_repair_name) {
                    self::$err_code = 400051;  //身份证号码已申请维修店
                    throw new \Exception('FAULT');
                }

                $data['member_id'] = $param['member_id'];
                $insert_id = Db::table('mob_repair')->insertGetId($data);

                //pj增加维修的业务经营范围
                $item_data = [
                    'maintenance_item_id' => 2,
                    'repair_id' => $insert_id
                ];
                Db::table('mob_repair_maintenance_server_item')->insert($item_data);

            }


            $audit_data = [
                'obj_id' => $insert_id,
                'model' => 'repair',
                'audit_status' => 1,
                'audit_time' => time()
            ];
            Db::table('mob_audit_log')->insert($audit_data);  // 增加审核记录   已提交

            Db::commit();
            return ['data' => ['repair_id' => $insert_id], 'code' => 200, 'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    //设置维修店主营品牌接口
    static public function repair_brand($param)
    {
        if (!isset($param['member_id']) || !isset($param['repair_id'])
            || !isset($param['brands'])
        ) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $data = [
                'brands' => $param['brands']
            ];
            $rs = Db::table('mob_repair_brand')->where("repair_id", $param['repair_id'])->select();
            if ($rs) {
                Db::table('mob_repair_brand')->where("repair_id", $param['repair_id'])->update($data);
            } else {
                $data["repair_id"] = $param['repair_id'];
                Db::table('mob_repair_brand')->insert($data);
            }
            Db::commit();
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    //设置维修店主营项目接口
    static public function repair_maintenance_server_item($param)
    {
        if (!isset($param['member_id']) || !isset($param['repair_id'])
            || !isset($param['Items'])
        ) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $Items_arr = explode(",", $param['Items']);
            //array_diff(a1,a2);
            $maintenance_item_id_arr = Db::table('mob_repair_maintenance_server_item')->where("repair_id", $param['repair_id'])->column('maintenance_item_id');
            if ($maintenance_item_id_arr) {
                //处理缺少的
                $maintenance_item_id_diff = array_diff($maintenance_item_id_arr, $Items_arr);
                if ($maintenance_item_id_diff) {
                    Db::table('mob_repair_maintenance_server_item')->where("maintenance_item_id", "in", $maintenance_item_id_diff)->delete();
                }
                //处理增加的
                $Items_diff = array_diff($Items_arr, $maintenance_item_id_arr);
                if ($Items_diff) {
                    for ($i = 0; $i < count($Items_diff); $i++) {
                        $data[] = [
                            'maintenance_item_id' => $Items_diff[$i]
                            , 'repair_id' => $param['repair_id']
                        ];
                    }
                    Db::table('mob_repair_maintenance_server_item')->insertAll($data);
                }
            } else {
                //直接增加
                for ($i = 0; $i < count($Items_arr); $i++) {
                    $data[] = [
                        'maintenance_item_id' => $Items_arr[$i]
                        , 'repair_id' => $param['repair_id']
                    ];
                }
                Db::table('mob_repair_maintenance_server_item')->insertAll($data);
            }
            Db::commit();
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取维修店列表接口
    static public function get_repair_list($param)
    {
        if (!isset($param['member_id'])) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        try {
            $order = ''; // 初始化排序
            if (isset($param['region_id']) && !empty($param['region_id']) && isset($param['level']) && !empty($param['level'])) {
                // 根据合伙人的等级和负责地区获取  下属维修店
                $level_array = ['', 'province', 'city', 'area', 'street'];
                $field = $level_array[$param['level']];
                $where = [
                    $field => $param['region_id']
                ];
                if (isset($param['status']) && !empty($param['status'])) {
                    $where['audit_status'] = $param['status'];
                } else {
                    $where['audit_status'] = 4;
                }
                if (isset($param['rand']) && !empty($param['rand']) && isset($param['order_by']) && !empty($param['order_by'])) {
                    $rands = ['', 'id', 'audit_time'];
                    $by = ['', 'asc', 'desc'];
                    $order = $rands[$param['rand']] . ' ' . $by[$param['order_by']];
                }
            }

            if (isset($param['lat']) && !empty($param['lat']) && isset($param['lon']) && !empty($param['lon'])) {
                if (!isset($param['radius']) || $param['radius'] < 1000) {
                    $radius = 1000;
                } else
                    $radius = $param['radius'];

                // 根据用户所在坐标，以及半径范围  获取维修店列表
                // 获取范围内的坐标值
                $coord = getAround($param['lat'], $param['lon'], $radius);
                $where = 'lat > ' . $coord[0] . ' AND lat < ' . $coord[1] . ' AND lon > ' . $coord[2] . ' AND lon < ' . $coord[3] . ' AND audit_status = 4';
            }
            if (!$where) {
                // 如果既没有根据合伙人获取列表   也没有根据经纬度获取列表   则标识参数错误
                self::$err_code = 400001;
                throw new \Exception('FAULT');
            }
            $repair_list = Db::table('mob_repair')->where($where)->order($order)->select();
            return ['data' => $repair_list, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取维修店详情接口
    static public function get_repair_info($param)
    {
        if (!isset($param['repair_id'])) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }
        try {

            $repair = Db::table('mob_repair')->where('id',$param['repair_id'])->find();

            // 获取维修店地址
            $region = Db::table('mob_region')->where('region_id', 'in', [$repair['province'], $repair['city'], $repair['area'], $repair['street']])->order('region_id asc')->select();
            $address = '';
            foreach ($region as $r) {
                $repair['province'] = $r['region_name'];
                $repair['city'] = $r['region_name'];
                $repair['area'] = $r['region_name'];
                $repair['street'] = $r['region_name'];
                $address .= $r['region_name'];
            }
            $repair['address'] = $address.$repair['address'];
            // 获取维修店主营项目
            $server_item = Db::table('mob_repair_maintenance_server_item')->alias('rsi')->field('si.*')
                ->join("mob_server_items si", "si.id = rsi.maintenance_item_id AND si.status = 1")
                ->where('repair_id', $param['repair_id'])->select();
            $repair['server_item'] = $server_item;

            return ['data' => $repair, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取维修店服务单列表接口
    static public function get_repair_server_order_list($param)
    {
        if (!isset($param['member_id']) || !isset($param['repair_id'])
            || !isset($param['start_time']) || !isset($param['end_time'])
        )
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        try {
            $where = ['repair_id' => $param['repair_id']];
            if ($param['start_time']) {
                $where["add_time"] = array('egt', $param['start_time']);
            }
            if ($param['end_time']) {
                $where["add_time"] = array('elt', $param['end_time']);
            }
            $order_server_list = Db::table('mob_order_server')->where($where)->select();
            return ['data' => $order_server_list, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取维修店优惠券列表接口
    static public function get_repair_coupon_list($param)
    {
        if (!isset($param['member_id']) || !isset($param['type'])) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }
        try {
            $where = [
                'member_id' => $param['member_id']
                , 'coupon_type' => $param['type']
            ];
            $coupon = Db::table('mob_coupon')->where($where)->select();
            return ['data' => $coupon, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 添加维修店自定义产品保存接口
    static public function repair_add_product($param)
    {
        if (!isset($param['repair_id'])
            || !isset($param['name'])
            || !isset($param['price'])
            || !isset($param['service_expires'])
        ) {
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        }

        $data = [
            'repair_id' => $param['repair_id'],
            'name' => $param['name'],
            'price' => $param['price'],
            'img1' => $param['img1'] ? $param['img1'] : '',
            'img2' => $param['img2'] ? $param['img2'] : '',
            'img3' => $param['img3'] ? $param['img3'] : '',
            'img4' => $param['img4'] ? $param['img4'] : '',
            'img5' => $param['img5'] ? $param['img5'] : '',
            'service_expires' => $param['service_expires'],
            'add_time' => time()
        ];

        // 启动事务
        Db::startTrans();
        try {
            $repair_product_id = Db::table('mob_repair_product')->insertGetId($data);
            Db::commit();
            return ['data' => ['id' => $repair_product_id, 'img' => $data['img1']], 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取维修店业务首页数据
    static public function repair_index_data($param)
    {
        if (!isset($param['member_id'])) return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        try {
            // 维修店信息
            $data = [
                'order_price_sum' => '0.00',
                'order_count' => '0',
                'distribution_money_all' => '0.00',
                'level_avg' => '5.0',
                'lat' => 0,
                'lon' => 0
            ];

            //维修店定位
            $where = ' member_id=' . $param['member_id'] . ' ';
            $repair = Db::table('mob_repair')->field('id,repair_name,lat,lon')->where($where)->find();
            if ($repair) {
                $data['repair_name'] = $repair['repair_name'];
                $data['lat'] = $repair['lat'];
                $data['lon'] = $repair['lon'];
            }

            $toDayBegin = strtotime(date("Y-m-d") . " 0:0:0");
            $toDayEnd = strtotime(date("Y-m-d") . " 23:59:60");

            //今日收入
            $where = ' repair_id=' . $repair['id'] . ' and finish_time>=' . $toDayBegin . ' and finish_time<=' . $toDayEnd . ' ';
            $order = Db::table('mob_order_server')->field('sum(order_price) as order_price_sum')->where($where)->find();
            $data['order_price_sum'] = $order["order_price_sum"] ? $order["order_price_sum"] : '0.00';

            //今日订单
            $where = ' repair_id=' . $repair['id'] . ' and order_receiving_time>=' . $toDayBegin . ' and order_receiving_time<=' . $toDayEnd . ' ';
            $order = Db::table('mob_order_server')->field('count(id) as order_count')->where($where)->find();
            $data['order_count'] = $order["order_count"] ? $order["order_count"] : '0';

            //分销金额
            $where = ' id=' . $param['member_id'] . ' ';
            $member = Db::table('mob_member')->field('distribution_money_all')->where($where)->find();
            $data['distribution_money_all'] = $member["distribution_money_all"] ? $member["distribution_money_all"] : '0.00';

            //平均评价
            $comment = Db::table('mob_comment')->alias('c')->field('avg(level) as level_avg')
                ->join("mob_order_server o", " c.obj_id=o.repair_id ", 'LEFT')
                ->where(' o.repair_id=' . $repair['id'] . ' and c.type=2 ')->find();
            $data['level_avg'] = $comment["level_avg"] ? round($comment["level_avg"], 1) : '5.0';

            // 是否有新消息
            $msg_where = [
                'member_role' => 'repair',
                'member_id' => $param['member_id'],
                'status' => 0
            ];
            $data['new_msg_num'] = Db::table('mob_member_message')->where($msg_where)->count();

            return ['code' => 200, 'data' => $data, 'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    // 获取维修店业务订单列表数据
    static public function repair_get_orders($param)
    {
        if (!isset($param['member_id'])) return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        try {

            $where = ' member_id=' . $param['member_id'] . ' ';
            $repair = Db::table('mob_repair')->field('id,repair_name,lat,lon')->where($where)->find();
            $item = Db::table('mob_repair_maintenance_server_item')->field('maintenance_item_id')->where('repair_id',$repair['id'])->select();
            $item_arr = array();
            for($i=0;$i<count($item);$i++){
                $item_arr[$i] = $item[$i]["maintenance_item_id"];
            }
            $item_str = join(',',$item_arr);
            if($item_str){
                if( strpos($item_str,",") ){
                    $item_str = " AND o.type in (".$item_str.") ";
                }else{
                    $item_str = " AND o.type='".$item_str."' ";
                }
            }else{
                $item_str = "";
            }
            $coord = getAround($repair['lat'],$repair['lon'],100000);//10公里内的
            $where = ' o.status=1 '.$item_str.' AND o.lat > ' . $coord[0] . ' AND o.lat < ' . $coord[1] . ' AND o.lon > ' . $coord[2] . ' AND o.lon < ' . $coord[3] . ' ';
            $order_list = Db::table('mob_order_server')->alias('o')->field('o.*,si.item_name, mr.headimgurl')
                ->join('mob_server_items si', 'si.id = o.type', 'LEFT')
                ->join("mob_member_role_info mr", "o.member_id = mr.member_id and mr.type = 0", 'LEFT')
                ->where($where)->order("add_time desc")->paginate();
            return ['code' => 200, 'data' => $order_list, 'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

    }

    // 获取维修店业务订单列表数据(地图范围内)
    static public function repair_get_orders_map($param)
    {
        if (!isset($param['member_id'])
            || !isset($param['lng'])
            || !isset($param['lat'])
            || !isset($param['zoom'])
        ) return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        try {

            $get_juli = 1000;//距离米
            switch ($param['zoom']) {
                case 3:
                    $get_juli = 2000000;break;
                case 4:
                    $get_juli = 1500000;break;
                case 5:
                    $get_juli = 800000;break;
                case 6:
                    $get_juli = 400000;break;
                case 7:
                    $get_juli = 200000;break;
                case 8:
                    $get_juli = 100000;break;
                case 9:
                    $get_juli = 50000;break;
                case 10:
                    $get_juli = 25000;break;
                case 11:
                    $get_juli = 12000;break;
                case 12:
                    $get_juli = 6000;break;
                case 13:
                    $get_juli = 3000;break;
                case 14:
                    $get_juli = 1600;break;
                case 15:
                    $get_juli = 800;break;
                case 16:
                    $get_juli = 400;break;
                case 17:
                    $get_juli = 200;break;
                case 18:
                    $get_juli = 100;break;
                default:
                    $get_juli = 1000;
            }


            $where = ' member_id=' . $param['member_id'] . ' ';
            $repair = Db::table('mob_repair')->field('id,repair_name,lat,lon')->where($where)->find();
            $item = Db::table('mob_repair_maintenance_server_item')->field('maintenance_item_id')->where('repair_id',$repair['id'])->select();
            $item_arr = array();
            for($i=0;$i<count($item);$i++){
                $item_arr[$i] = $item[$i]["maintenance_item_id"];
            }
            $item_str = join(',',$item_arr);
            if($item_str){
                if( strpos($item_str,",") ){
                    $item_str = " AND o.type in (".$item_str.") ";
                }else{
                    $item_str = " AND o.type='".$item_str."' ";
                }
            }else{
                $item_str = "";
            }

            $coord = getAround($param['lat'], $param['lng'], $get_juli);
            $where = 'o.status=1 '.$item_str.' AND lat > ' . $coord[0] . ' AND lat < ' . $coord[1] . ' AND lon > ' . $coord[2] . ' AND lon < ' . $coord[3] . ' ';
            $order_list = Db::table('mob_order_server')->alias('o')->field('o.*,si.item_name,mr.headimgurl')
                ->join('mob_server_items si', 'si.id = o.type', 'LEFT')
                ->join("mob_member_role_info mr", "o.member_id = mr.member_id and mr.type = 0", 'LEFT')
                ->where($where)->order("add_time desc")->select();
            return ['code' => 200, 'data' => $order_list, 'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

    }

    // 获取维修订单数据
    static public function repair_order_info($param)
    {
        if (!isset($param['order_id'])) return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        // 启动事务
        Db::startTrans();
        try {

            $order_id = $param["order_id"];
            $order = Db::table('mob_order_server')->alias('o')->field('o.*,si.item_name,mr.headimgurl,mr.nickname,car.name as car_name')
                ->join('mob_server_items si', 'si.id = o.type', 'LEFT')
                ->join("mob_member_role_info mr", "o.member_id = mr.member_id and mr.type = 0", 'LEFT')
                ->join("mob_my_car car", "car.member_id = o.member_id", 'LEFT')
                ->where("o.id",$order_id)->find();
            //print_r($order);exit();

            if( !$order["order_price"] ) {
                $where = ' order_id="'.$order_id.'" ';
                $order["order_price"] = Db::table('mob_order_product_server')->where($where)->value('sum(product_price*product_num)');
                if( !$order["order_price"] ) {
                    $order["order_price"] = '0.00';
                }else{
                    $data = [
                        "order_price" => $order["order_price"]
                    ];
                    $update = Db::table('mob_order_server')->where("id",$order_id)->update($data);
                }
            }

            Db::commit();
            return ['code' => 200, 'data' => $order, 'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

    }

    // 获取售后单列表
    static public function repair_austin_list($param) {
        if(!isset($param['member_id']) || !isset($param['type']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $order_list = Db::table('mob_order_austin')->alias('oa')
                ->field('oa.*, r.logo, r.repair_name, o.order_price, op.product_image, op.product_name')
                ->join('mob_order_product_server op', 'op.id = oa.product_id')
                ->join('mob_order_server o', 'o.id = oa.order_id')
                ->join('mob_repair r', 'r.id = o.repair_id')
                ->where('r.member_id', $param['member_id'])->where('oa.type', $param['type'])->where('oa.status', 'in', '0, 1, 2, 3')->paginate();
            return ['data'=>$order_list->toArray(), 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取投诉单列表
    static public function repair_complaint_list($param) {
        if(!isset($param['member_id']) || !isset($param['type']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $order_list = Db::table('mob_order_austin')->alias('oa')
                ->field('oa.*, r.logo, r.repair_name, o.order_price, o.order_sn, op.product_image, op.product_name')
                ->join('mob_order_product_server op', 'op.id = oa.product_id')
                ->join('mob_order_server o', 'o.id = oa.order_id')
                ->join('mob_repair r', 'r.id = o.repair_id')
                ->where('r.member_id', $param['member_id'])->where('oa.type', $param['type'])->where('oa.status', 'in', '4， 5')->paginate();
            return ['data'=>$order_list->toArray(), 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取维修店店铺中心数据
    static public function repair_store_index($param) {
        if( !isset($param['member_id']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        try{
            $repair = Db::table('mob_repair')->where('member_id', $param['member_id'])->find();
            if (!$repair) {
                self::$err_code = 400138;
                throw new \Exception('FAULT');
            }
            $data = Registration::check_registration($param);
            $repair['qiandao'] = $data;
            $member = Db::table('mob_member')->where('id', $param['member_id'])->find();
            $repair['member'] = $member;

            $item = Db::table('mob_server_items')->alias('si')->field('si.*,ri.id as r_id')
                ->join('mob_repair_maintenance_server_item ri', ' ri.maintenance_item_id=si.id and ri.repair_id='.$repair["id"].' ', 'LEFT')
                ->where(" si.display=1 ")->group('si.id')->select();
            $repair["item"] = $item;

            // 获取首页订单统计数据
            $orders = Db::table('mob_order_server')->field('status, member_id, replytime, order_receiving_time, is_comment')->where('repair_id',$repair["id"])->select();
            //初始化 待抢单、 议价中、 待付款、 服务中、 待确认 统计数量
            $dqd = $yj = $dfk = $fwz = $dpj = 0;
            foreach ($orders as $o) {
                switch ($o['status']) {
                    case 1:
                        $dqd++;
                        break;
                    case 2:
                        $dfk++;
                        break;
                    case 3:
                        $fwz++;
                        break;
                    case 6:
                        if ($o['is_comment'] == 0) {
                            $dpj++;
                        }
                        break;
                    case 11:
                        $yj++;
                        break;
                }
            }
            $order_num = [
                'dqd' => $dqd,
                'yj' => $yj,
                'dfk' => $dfk,
                'fwz' => $fwz,
                'dpj' => $dpj,
            ];
            $repair['order_num'] = $order_num;

            // 获取首页售后统计数据
            $austin = Db::table('mob_order_austin')->field('status')->where('obj_id',$repair["id"])->where('type',2)->select();
            //初始化 售后处理状态 0 已提交  1同意 2不同意  3取消  4申诉  5关闭
            $tk = $ss = 0;
            foreach ($austin as $o) {
                switch ($o['status']) {
                    case 0:
                        $tk++;break;
                    case 4:
                        $ss++;break;
                }
            }
            $austin_num = [
                'tk' => $tk,
                'ss' => $ss
            ];
            $repair['austin_num'] = $austin_num;


            return ['data'=>$repair, 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 修改维修店店铺数据
    static public function repair_info_change($param) {
        if( !isset($param['member_id']) || !isset($param['fields']) || !isset($param['values']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        if( strpos(" ".$param['fields'],"ketubbah") ){
            return ['code' => 0, 'data' => '', 'msg'=> '禁止修改保障金'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $fArr = explode("[|]",$param['fields']);
            $vArr = explode("[|]",$param['values']);
            $data = [];
            for($i=0;$i<count($fArr);$i++){
                $data[$fArr[$i]] = $vArr[$i];
            }
            $update = Db::table('mob_repair')->where("member_id",$param['member_id'])->update($data);
            Db::commit();
            return ['code' => 200, 'data' => $update, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

    }

    // 修改维修店店鋪经营范围
    static public function repair_item_change($param) {
        if( !isset($param['member_id']) || !isset($param['dels']) || !isset($param['adds']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        // 启动事务
        Db::startTrans();
        try {
            $repair = Db::table('mob_repair')->where('member_id', $param['member_id'])->find();
            $repair_id = $repair["id"];
            if($param['dels']){
                $where = ' repair_id='.$repair_id.' and maintenance_item_id in ('.$param['dels'].') ';
                $delete = Db::table('mob_repair_maintenance_server_item')->where($where)->delete();
            }
            if($param['adds']){
                $data = [];
                $add_arr = explode(",",$param['adds']);
                for($i=0;$i<count($add_arr);$i++){
                    $data[$i] = [
                        "maintenance_item_id" => $add_arr[$i],
                        "repair_id" => $repair_id
                    ];
                }
                $insertAll = Db::table('mob_repair_maintenance_server_item')->insertAll($data);
            }
            Db::commit();
            return ['code' => 200, 'data' => '' ,'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

    }

    // 搜索维修店自定义产品接口
    static public function repair_so_product($param) {
        if( !isset($param['repair_id']) || !isset($param['keyword']) || !isset($param['page_no']) || !isset($param['page_size']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        try{
            // 获取订单列表接口
            if($param['keyword']){
                $where = " repair_id='".$param['repair_id']."' and instr(name,'".$param['keyword']."')>0 ";
            }else{
                $where = " repair_id='".$param['repair_id']."' ";
            }
            $goods = Db::table('mob_repair_product')->order("id desc")->where($where)->limit($param['page_no']*$param['page_size'],$param['page_size'])->select();
            return ['code' => 200, 'data' => $goods,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 添加推送订单服务或商品
    static public function repair_order_product_server_add($param) {
        if( !isset($param['order_id']) || !isset($param['repair_id']) || !isset($param['product_id'])
            || !isset($param['product_name']) || !isset($param['product_num']) || !isset($param['product_price'])
            || !isset($param['product_image']) || !isset($param['type']) || !isset($param['server_time'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $repair_id = $param['repair_id'];

            $order_id = $param['order_id'];
            $product_id = $param['product_id'];
            $product_name = $param['product_name'];
            $product_num = $param['product_num'];
            $product_price = $param['product_price'];
            $product_attr_id = $param['product_attr_id'];
            $product_image = $param['product_image'];
            $type = $param['type'];
            $msg = $param['msg'];
            $server_time = $param['server_time'];

            $where = " o.id='".$order_id."' ";
            $order_info = Db::table('mob_order_server')->alias('o')->field('o.*,r.repair_name')
                ->join('mob_repair r', ' r.id=o.repair_id ', 'LEFT')
                ->where($where)->find();
            if($order_info["repair_id"]!=$repair_id){
                return ['data'=>'', 'code'=>0, 'msg'=> '这不是你接到的订单，无权操作'];
            }
//            if($order_info["status"]!=11){
//                return ['data'=>$order_info["status"], 'code'=>400057, 'msg'=> get_server_order_status($order_info["status"])];
//            }

            $data = [
                "order_id" => $order_id,
                "product_id" => $product_id,
                "product_name" => $product_name,
                "product_num" => $product_num,
                "product_price" => $product_price,
                "product_attr_id" => $product_attr_id,
                "product_image" => $product_image?$product_image:'/static/wechat/images/fuwu.png',
                "type" => $type,
                "msg" => $msg,
                "server_time" => $server_time
            ];

            $p_s_id = Db::table('mob_order_product_server')->insertGetId($data);
            Db::commit();

            if($p_s_id){
                return ['code' => 200, 'data' => $p_s_id,'msg'=> 'SUCCESS'];
            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }



    }

    // 修改推送订单服务或商品的数量
    static public function repair_order_product_server_update($param) {
        if( !isset($param['id']) || !isset($param['order_id']) || !isset($param['product_num'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $where = [
                'id' => intval($param['id']),
                'order_id' => intval($param['order_id'])
            ];
            $data = [
                'product_num' => intval($param['product_num'])
            ];

            $update = Db::table('mob_order_product_server')->where($where)->update($data);
            Db::commit();
            if($update){
                return ['code' => 200, 'data' => intval($param['product_num']),'msg'=> 'SUCCESS'];
            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }



    }

    // 删除推送订单服务或商品
    static public function repair_order_product_server_delete($param) {
        if( !isset($param['id']) || !isset($param['order_id'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $where = [
                'id' => intval($param['id']),
                'order_id' => intval($param['order_id'])
            ];

            $update = Db::table('mob_order_product_server')->where($where)->delete();
            if($update){
                //nothing
            }
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

        return ['code' => 200, 'data' => '','msg'=> 'SUCCESS'];


    }

    // 确认推送订单
    static public function repair_order_push($param) {
        if( !isset($param['order_id']) || !isset($param['repair_id']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {

            $order_id = $param['order_id'];
            $repair_id = $param['repair_id'];
            $order_info = Db::table('mob_order_server')->alias('o')->field('o.*,r.repair_name')
                ->join('repair r', ' r.id=o.repair_id ', 'LEFT')
                ->where("o.id",$order_id)->find();
            $price_sum = Db::table('mob_order_product_server')->where("order_id",$order_id)->sum('product_num*product_price');
            $where = [
                "id" => $order_id,
                "repair_id" => $repair_id
            ];
            $data = [
                "status" => 2,
                "order_price" => $price_sum
            ];
            $update = Db::table('mob_order_server')->where($where)->update($data);

            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

        if($update){
            // 发送微信模板消息
            $openid = Db::table('mob_member')->where(' id="'.$order_info["member_id"].'" ')->value('openid');
            $url = 'http://'.$_SERVER["HTTP_HOST"].'/wechat/orders/order_info/id/' . $order_id;
            if ($openid) {
                $data = [
                    'touser' => $openid,
                    'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
                    'url' => $url,
                    'topcolor' => '#FF0000',
                    'data' => [
                        'first' => [
                            'value' => '维修店订单推送',
                            "color" => "#173177"
                        ],
                        'keyword1' => [
                            'value' => '订单推送',
                            "color" => "#173177"
                        ],
                        'keyword2' => [
                            'value' => date('Y-m-d H:i:s'),
                            "color" => "#173177"
                        ],
                        'remark' => [
                            'value' => '请尽快支付',
                            "color" => "#173177"
                        ]
                    ]
                ];
                send_msg($data);

                /*推送站内信息*/
                $param = [
                    'member_id' => $order_info['member_id'],
                    'member_role' => 'member',
                    'msg_id' => 50,
                ];
                $params = [
                    $order_info["repair_name"],$order_info['order_sn'],$price_sum,date('Y-m-d H:i:s'),'url' => $url
                ];
                Message::creation_order_msg($param,$params);

            }
        }
        return ['code' => 200, 'data' => '','msg'=> 'SUCCESS'];

    }

    // 搜索维修店历史推送订单的用户接口
    static public function repair_order_push_history($param) {
        if( !isset($param['repair_id']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        try{
            $where = " o.repair_id='".$param['repair_id']."' ";
            $order = db('order_server')->alias('o')->field('o.id,o.apply_person,o.phone,mr.headimgurl,mr.nickname')
                ->join("mob_member_role_info mr", "o.member_id = mr.member_id and mr.type = 0", 'LEFT')
                ->order("o.id desc")->group('o.member_id')->where($where)->paginate();
            return ['code' => 200, 'data' => $order,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 根据手机号码创建直接推送的订单
    static public function repair_phone_so_order($param) {
        if( !isset($param['repair_id']) || !isset($param['phone']) || !isset($param['source']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{

            $repair = Db::table('mob_repair')->field('repair_name,lat,lon')->where('id',$param['repair_id'])->where('audit_status',4)->find();
            if(!$repair){
                self::$err_code = 400136;
                throw new \Exception('FAULT');
            }
            $member = Db::table('mob_member')->field('id')->where('phone',$param['phone'])->find();
            if(!$repair){
                self::$err_code = 400029;
                throw new \Exception('FAULT');
            }

            //组装数据
            $order_sn = date("YmdHis") . rand(10000, 99999);
            $data['order_sn'] = $order_sn; //订单号
            $data['member_id'] = $member['id']; // 用户ID
            $data['repair_id'] = $param['repair_id']; // 维修店ID
//            $data['type'] = $param['type']; //需求类型 1、图片  2、拖车  3、维修  4、保养
            $data['add_time'] = time();  // 申请时间
            $data['push_time'] = time();  // 下单成功立即推送
            $data['status'] = 11;  // 下单成功（直接议价推送）
            $data['msg'] = "(维修店自定义推送)";  // 需求描述
//            $data['service_time'] = $param['service_time'];  // 服务时间
            $data['phone'] = $param['phone']; // 联系电话
//            $data['service_mode'] = $param['service_mode']; // 处理方式 1、上门；  2、到店
//            $data['province'] = get_region($param['province']); // 省
//            $data['city'] = get_region($param['city']); // 市
//            $data['area'] = get_region($param['area']); // 区
//            $data['street'] = get_region($param['street']); // 街道
//            $data['address'] = $param['address']; // 详细地址
            $data['lat'] = $repair['lat']; // 纬度
            $data['lon'] = $repair['lon']; // 经度
            $data['order_receiving_time'] = time();  // 接单时间
            $data['overtime'] = time() + 600;  // 议价结束时间  10分钟
            $data['source'] = $param['source'];  // 订单来源

            $order_id = Db::table('mob_order_server')->insertGetId($data);

            Db::commit();
            return ['data'=>['id' => $order_id], 'code'=>200, 'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 生成扫码支付订单
    static public function creation_scan_code_pay_order($param) {
        if(!isset($param['member_id']) || !isset($param['member_type'])
            || !isset($param['money']) || !isset($param['obj_id']) || !isset($param['obj_type']) || !isset($param['source'])){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        try {
            $order_sn = '105' . date("YmdHis") . rand(10000, 99999); //扫码支付订单号
            $scan_pay_models = ['', 'repair', 'dealer', 'partner'];
            $scan_pay_model = $scan_pay_models[$param['obj_type']];  // 获取对应角色的 member_id
            $member_id = Db::table('mob_' . $scan_pay_model)->where('id', $param['obj_id'])->value('member_id');
            $data = [
                'member_id' => $param['member_id'],  // 下单用户ID
                'member_type' => $param['member_type'],  // 下单用户角色
                'obj_id' => $param['obj_id'],  // 收款角色ID
                'obj_member_id' => $member_id,  // 收款角色member_id
                'obj_type' => $param['obj_type'],  // 收款用户角色
                'order_sn' => $order_sn,
                'order_price' => $param['money'],
                'add_time' => time(),
                'source' => $param['source'],
            ];
            $order_id = db('order_scan_code_pay')->insertGetId($data);

            $data['id'] = $order_id;
            return ['code' => 200, 'data' => $data, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    
//====================================销售采购============================================

    // 搜索维修店历史销售订单的用户接口
    static public function repair_deal_push_history($param) {
        if( !isset($param['repair_id']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }
        try{
            $where = " o.repair_id='".$param['repair_id']."' ";
            $order = db('order_server_deal')->alias('o')->field('o.id,o.apply_person,o.phone,r.logo,r.repair_name,r.phone as r_phone')
                ->join("mob_repair r", "o.repair_id_to = r.id ", 'LEFT')
                ->order("o.id desc")->group('o.repair_id_to')->where($where)->paginate();
            return ['code' => 200, 'data' => $order,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 根据手机号码创建直接推送的维修店商品销售订单
    static public function repair_phone_so_deal($param) {
        if( !isset($param['repair_id']) || !isset($param['phone']) || !isset($param['source']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{

            $repair = Db::table('mob_repair')->where('id',$param['repair_id'])->where('audit_status',4)->find();
            if(!$repair){
                self::$err_code = 400136;
                throw new \Exception('FAULT');
            }
            $repair_to = Db::table('mob_member')->alias('m')->field('r.*,m.openid')
                ->join('mob_repair r', ' r.member_id = m.id', 'LEFT')
                ->where('m.phone',$param['phone'])->where('r.audit_status',4)->find();
            if(!$repair_to){
                self::$err_code = 400029;
                throw new \Exception('FAULT');
            }
            //不能给自己发
            if($repair["id"]==$repair_to["id"]){
                self::$err_code = 400009;
                throw new \Exception('FAULT MY');
            }


            //组装数据
            $order_sn = date("YmdHis") . rand(10000, 99999);
            $data['order_sn'] = $order_sn; //订单号
            $data['member_id_to'] = $repair_to['member_id']; // 用户ID
            $data['repair_id_to'] = $repair_to['id']; // 用户ID
            $data['member_id'] = $repair['member_id']; // 用户ID
            $data['repair_id'] = $repair['id']; // 维修店ID
//            $data['type'] = $param['type']; //需求类型 1、图片  2、拖车  3、维修  4、保养
            $data['add_time'] = time();  // 申请时间
            $data['push_time'] = time();  // 下单成功立即推送
            $data['status'] = 0;  // 下单
            $data['msg'] = "(维修店自定义销售)";  // 需求描述
//            $data['service_time'] = $param['service_time'];  // 服务时间
            $data['phone'] = $param['phone']; // 联系电话
//            $data['service_mode'] = $param['service_mode']; // 处理方式 1、上门；  2、到店
//            $data['province'] = get_region($param['province']); // 省
//            $data['city'] = get_region($param['city']); // 市
//            $data['area'] = get_region($param['area']); // 区
//            $data['street'] = get_region($param['street']); // 街道
            $data['address'] = $repair_to['address']; // 详细地址
            $data['lat'] = $repair_to['lat']; // 纬度
            $data['lon'] = $repair_to['lon']; // 经度
            $data['order_receiving_time'] = time();  // 接单时间
            $data['overtime'] = time() + 600;  // 议价结束时间  10分钟
            $data['source'] = $param['source'];  // 订单来源

            $order_id = Db::table('mob_order_server_deal')->insertGetId($data);

            Db::commit();
            return ['data'=>['id' => $order_id], 'code'=>200, 'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 获取维修店销售采购订单数据
    static public function repair_deal_info($param)
    {
        if (!isset($param['order_id'])) return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        // 启动事务
        Db::startTrans();
        try {

            $order_id = $param["order_id"];
            $order = Db::table('mob_order_server_deal')->alias('o')->field('o.*,si.item_name,mr.logo,mr.repair_name')
                ->join('mob_server_items si', 'si.id = o.type', 'LEFT')
                ->join("mob_repair mr", " o.repair_id_to = mr.id ", 'LEFT')
                ->where("o.id",$order_id)->find();
            //print_r($order);exit();

            if( !$order["order_price"] ) {
                $where = ' order_id="'.$order_id.'" ';
                $order["order_price"] = Db::table('mob_order_product_server_deal')->where($where)->value('sum(product_price*product_num)');
                if( !$order["order_price"] ) {
                    $order["order_price"] = '0.00';
                }else{
                    $data = [
                        "order_price" => $order["order_price"]
                    ];
                    $update = Db::table('mob_order_server_deal')->where("id",$order_id)->update($data);
                }
            }

            Db::commit();
            return ['code' => 200, 'data' => $order, 'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

    }

    // 添加维修店销售订单商品
    static public function repair_order_product_server_deal_add($param) {
        if( !isset($param['order_id']) || !isset($param['repair_id']) || !isset($param['product_id'])
            || !isset($param['product_name']) || !isset($param['product_num']) || !isset($param['product_price'])
            || !isset($param['product_image']) || !isset($param['type']) || !isset($param['server_time'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $repair_id = $param['repair_id'];

            $order_id = $param['order_id'];
            $product_id = $param['product_id'];
            $product_name = $param['product_name'];
            $product_num = $param['product_num'];
            $product_price = $param['product_price'];
            $product_attr_id = $param['product_attr_id'];
            $product_image = $param['product_image'];
            $type = $param['type'];
            $msg = $param['msg'];
            $server_time = $param['server_time'];

            $where = " o.id='".$order_id."' ";
            $order_info = Db::table('mob_order_server_deal')->alias('o')->field('o.*,r.repair_name')
                ->join('mob_repair r', ' r.id=o.repair_id ', 'LEFT')
                ->where($where)->find();
            if($order_info["repair_id"]!=$repair_id){
                return ['data'=>'', 'code'=>0, 'msg'=> '这不是你接到的订单，无权操作'];
            }
//            if($order_info["status"]!=0){
//                return ['data'=>$order_info["status"], 'code'=>400057, 'msg'=> get_server_order_status($order_info["status"])];
//            }

            $data = [
                "order_id" => $order_id,
                "product_id" => $product_id,
                "product_name" => $product_name,
                "product_num" => $product_num,
                "product_price" => $product_price,
                "product_attr_id" => $product_attr_id,
                "product_image" => $product_image?$product_image:'/static/wechat/images/fuwu.png',
                "type" => $type,
                "msg" => $msg,
                "server_time" => $server_time
            ];

            $p_s_id = Db::table('mob_order_product_server_deal')->insertGetId($data);
            Db::commit();

            if($p_s_id){
                return ['code' => 200, 'data' => $p_s_id,'msg'=> 'SUCCESS'];
            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }



    }

    // 修改推送销售订单商品的数量
    static public function repair_order_product_server_deal_update($param) {
        if( !isset($param['id']) || !isset($param['order_id']) || !isset($param['product_num'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $where = [
                'id' => intval($param['id']),
                'order_id' => intval($param['order_id'])
            ];
            $data = [
                'product_num' => intval($param['product_num'])
            ];

            $update = Db::table('mob_order_product_server_deal')->where($where)->update($data);
            Db::commit();
            if($update){
                return ['code' => 200, 'data' => intval($param['product_num']),'msg'=> 'SUCCESS'];
            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }



    }

    // 删除维修店销售订单商品
    static public function repair_order_product_server_deal_delete($param) {
        if( !isset($param['id']) || !isset($param['order_id'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {
            $where = [
                'id' => intval($param['id']),
                'order_id' => intval($param['order_id'])
            ];

            $update = Db::table('mob_order_product_server_deal')->where($where)->delete();
            if($update){
                //nothing
            }
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

        return ['code' => 200, 'data' => '','msg'=> 'SUCCESS'];


    }

    // 确认推送维修店销售订单
    static public function repair_deal_push($param) {
        if( !isset($param['order_id']) || !isset($param['repair_id']) ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try {

            $order_id = $param['order_id'];
            $repair_id = $param['repair_id'];
            $order_info = Db::table('mob_order_server_deal')->alias('o')->field('o.*,r.repair_name')
                ->join('mob_repair r', ' r.id=o.repair_id ', 'LEFT')
                ->where("o.id",$order_id)->find();
            $price_sum = Db::table('mob_order_product_server_deal')->where("order_id",$order_id)->sum('product_num*product_price');
            if(!$price_sum){
                return ['data'=>'', 'code'=>400062, 'msg'=> 'FAULT'];
            }

            $where = [
                "id" => $order_id,
                "repair_id" => $repair_id
            ];
            $data = [
                "status" => 2,
                "order_price" => $price_sum
            ];
            $update = Db::table('mob_order_server_deal')->where($where)->update($data);
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }

        if($update){
            // 发送微信模板消息
            $member_to = Db::table('mob_repair')->alias('r')->field('m.id,m.openid')
                ->join('mob_member m', ' r.member_id=m.id ', 'LEFT')
                ->where(' r.id="'.$order_info["repair_id_to"].'" ')->find();
            $url = 'http://'.$_SERVER["HTTP_HOST"].'/wechat/r_orders/server_deal_goods_pay/order_id/' . $order_id;
            if ($member_to['openid']) {
                $data = [
                    'touser' => $member_to['openid'],
                    'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
                    'url' => $url,
                    'topcolor' => '#FF0000',
                    'data' => [
                        'first' => [
                            'value' => '维修店订单推送',
                            "color" => "#173177"
                        ],
                        'keyword1' => [
                            'value' => '订单推送',
                            "color" => "#173177"
                        ],
                        'keyword2' => [
                            'value' => date('Y-m-d H:i:s'),
                            "color" => "#173177"
                        ],
                        'remark' => [
                            'value' => '请尽快支付',
                            "color" => "#173177"
                        ]
                    ]
                ];
                send_msg($data);

                /*推送站内信息*/
                $param = [
                    'member_id' => $member_to['id'],
                    'member_role' => 'repair',
                    'msg_id' => 50,
                ];
                $params = [
                    $order_info["repair_name"],$order_info['order_sn'],$price_sum,date('Y-m-d H:i:s'),'url' => $url
                ];
                Message::creation_order_msg($param,$params);

            }
        }
        return ['code' => 200, 'data' => '','msg'=> 'SUCCESS'];

    }

}





